package com.yonyou.cyxdms.sysAuth.service.service.version;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.entity.AppVersionPO;
import com.yonyou.cyxdms.sysAuth.service.feign.FileServiceClient;
import com.yonyou.cyxdms.sysAuth.service.mapper.AppVersionMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.SystemParamMapper;
import com.yonyou.cyxdms.sysAuth.service.service.SystemParamService;
import com.yonyou.cyxdms.sysAuth.service.service.dealerchannel.DealerInfoServiceImpl;
import com.yonyou.cyxdms.sysAuth.service.vo.appversion.AppVersionVO;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.AppVersionDto;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.List;


/**
 * <p>
 * 组织 服务实现类
 * </p>
 *
 * @author maxingjian
 * @since 2019-08-26
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class VersionServiceImpl implements VersionService {

    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(DealerInfoServiceImpl.class);

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    FileServiceClient fileServiceClient;

    @Autowired
    SystemParamService systemParamService;

    @Value("${ios.title}")
    private String title;

    @Value("${ios.path}")
    private String path;

    @Value("${ios.bundleId}")
    private String bundleId;

    @Override
    public String insertAppVersion(AppVersionVO appVersionVO) throws Exception {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        appVersionMapper.updateVersionStatus(loginInfoDto.getAppId(), appVersionVO.getAppType());
        AppVersionPO appversionpo = new AppVersionPO();
        BeanMapperUtil.copyPropertiesWithOutNull(appVersionVO, appversionpo);
        if ("IOS".equals(appVersionVO.getAppType())) {
            String fileUrl = appVersionVO.getUrl();
            String versionCode = appVersionVO.getVersionNo();
            String titleQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.TITLE,loginInfoDto.getAppId());
            String bundleIdQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.BUNDLE_ID,loginInfoDto.getAppId());
            String pathQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.PLIST_FILE,loginInfoDto.getAppId());
            String restUrl = createPlist((StringUtils.isNullOrEmpty(titleQ)?title:titleQ), (StringUtils.isNullOrEmpty(pathQ)?path:pathQ), (StringUtils.isNullOrEmpty(bundleIdQ)?bundleId:bundleIdQ), fileUrl, versionCode);
            //String restUrl = fileServiceClient.upload(path).getData();
            logger.debug("IOS通过平台返回路径：{}", "itms-services://?action=download-manifest&url=" + restUrl);
            appversionpo.setUrl("itms-services://?action=download-manifest&url=" + restUrl);
        }
        appVersionMapper.insert(appversionpo);
        String messageFormat = BaseDataCommonConstants.VERSION_CACHE_TYPE;
        redisClient.hdel(messageFormat, appVersionVO.getAppType() + loginInfoDto.getAppId());

        AppVersionDto dto = new AppVersionDto();
        BeanUtils.copyProperties(appversionpo, dto);
        redisClient.hsetExpire(messageFormat, appVersionVO.getAppType() + loginInfoDto.getAppId(), JSONUtil.objectToJson(dto), SysAuthCommonConstants.EXPIRE_TIME_ONE_HOUR);

        return "";
    }

    @Override
    public IPage<AppVersionVO> queryAppVersion(Page page) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return appVersionMapper.queryAppVersion(page, loginInfoDto.getAppId());
    }

    @Override
    public AppVersionVO queryAppVersionById(String id) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return appVersionMapper.queryAppVersionById(id, loginInfoDto.getAppId());
    }

    @Override
    public String updateAppVersion(AppVersionVO appVersionVO) throws Exception {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        AppVersionPO appversionpo = appVersionMapper.selectById(appVersionVO.getVersionId());
        appversionpo.setRemark(appVersionVO.getRemark());
        if (!StringUtils.isNullOrEmpty(appVersionVO.getUrl()) && !appVersionVO.getUrl().equals(appversionpo.getUrl())) {
            appversionpo.setUrl(appVersionVO.getUrl());
            if ("IOS".equals(appVersionVO.getAppType())) {
                String fileUrl = appVersionVO.getUrl();
                String versionCode = appVersionVO.getVersionNo();
                String titleQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.TITLE,loginInfoDto.getAppId());
                String bundleIdQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.BUNDLE_ID,loginInfoDto.getAppId());
                String pathQ = systemParamService.getParamValueByCode(SysAuthCommonConstants.PLIST_FILE,loginInfoDto.getAppId());
                String restUrl = createPlist((StringUtils.isNullOrEmpty(titleQ)?title:titleQ), (StringUtils.isNullOrEmpty(pathQ)?path:pathQ), (StringUtils.isNullOrEmpty(bundleIdQ)?bundleId:bundleIdQ), fileUrl, versionCode);
                // String restUrl = fileServiceClient.uploadUrl(path).getData();
                logger.debug("IOS上传通过平台返回url路径：{}", "itms-services://?action=download-manifest&url=" + restUrl);
                appversionpo.setUrl("itms-services://?action=download-manifest&url=" + restUrl);
            }
        }
        appVersionMapper.updateById(appversionpo);

        String messageFormat = BaseDataCommonConstants.VERSION_CACHE_TYPE;
        redisClient.hdel(messageFormat, appVersionVO.getAppType() + loginInfoDto.getAppId());

        AppVersionDto dto = new AppVersionDto();
        BeanUtils.copyProperties(appversionpo, dto);
        redisClient.hsetExpire(messageFormat, appVersionVO.getAppType() + loginInfoDto.getAppId(), JSONUtil.objectToJson(dto), SysAuthCommonConstants.EXPIRE_TIME_ONE_HOUR);
        return "";
    }

    @Override
    public List<AppVersionVO> queryAppVersionByApp() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return appVersionMapper.queryAppVersionByAppId(SysAuthDictCodeConstants.STATUS_IS_VALID, loginInfoDto.getAppId(),null);
    }

    @Override
    public AppVersionVO queryDataByAppType(String appDownLoadType,String appId)
    {
        List<AppVersionVO> list= appVersionMapper.queryAppVersionByAppId(SysAuthDictCodeConstants.STATUS_IS_VALID, appId,appDownLoadType);
        if(list.size()>0) {
            return list.get(0);
        }
        return null;
    }


    public static void main(String[] args) throws Exception {
        String title = "AddressChange";
        String path = "d:/manifest.plist";
        String bundleId = "com.addresschange.ccss";
        String fileUrl = "163.com";
        String versionCode = "1.2.3";
        VersionServiceImpl mp = new VersionServiceImpl();
        mp.createPlist(title, path, bundleId, fileUrl, versionCode);
    }

    public String createPlist(String title, String path, String bundleId, String fileUrl, String versionCode) throws Exception {
        logger.info("开始创建plist文件");
        String url = "";
        File file = new File(path);
        if (!file.exists()) {
            try {
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    throw new ServiceBizException("创建plist文件目录异常");
                }
            } catch (IOException e) {
                throw new IOException(e);
            }
        }
        String plist = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
                + "<plist version=\"1.0\">\n" + "<dict>\n"
                + "<key>items</key>\n"
                + "<array>\n"
                + "<dict>\n"
                + "<key>assets</key>\n"
                + "<array>\n"
                + "<dict>\n"
                + "<key>kind</key>\n"
                + "<string>software-package</string>\n"
                + "<key>url</key>\n"
                // 之前所上传的ipa文件路径（必须是https，否则无法下载！）
                + "<string>" + fileUrl + "</string>\n"
                + "</dict>\n"
                + "</array>\n"
                + "<key>metadata</key>\n"
                + "<dict>\n"
                + "<key>bundle-identifier</key>\n"
                // 这个是开发者账号用户名，也可以为空，为空安装时看不到图标，完成之后可以看到
                + "<string>" + bundleId + "</string>\n"
                + "<key>bundle-version</key>\n"
                // 版本号
                + "<string>" + versionCode + "</string>\n"
                + "<key>kind</key>\n"
                + "<string>software</string>\n"
                + " <key>platform-identifier</key>\n"
                + " <string>com.apple.platform.iphoneos</string>\n"
                + "<key>title</key>\n"
                // 一定要有title，否则无法正常下载
                + "<string>" + title + "</string>\n"
                + "</dict>\n"
                + "</dict>\n"
                + "</array>\n"
                + "</dict>\n"
                + "</plist>";
        //FileOutputStream output = null;
        //OutputStreamWriter writer = null;
        try(FileOutputStream output = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8")) {
     /*       output = new FileOutputStream(file);
            writer = new OutputStreamWriter(output, "UTF-8");*/
            writer.write(plist);
            writer.close();
            output.close();
            logger.info("成功创建plist文件");
        } catch (Exception e) {
            throw new ServiceBizException("创建plist文件目录异常");
        }/*finally {
            if (output != null) {
                output.close();
            }
            if (writer != null) {
                writer.close();
            }
        }*/


        MultipartFile multipartFile = getMulFileByPath(path);

//        File fileLoad = new File(path);
//        logger.debug("文件路径：{}",path);
//        FileItemFactory factory = new DiskFileItemFactory(16, null);
//        FileItem item = factory.createItem(fileLoad.getName(), "text/plain", true, fileLoad.getName());
//        logger.debug("文件路径获取名称：{}",fileLoad.getName());
//        MultipartFile multipartFile = new CommonsMultipartFile(item);
        url = fileServiceClient.upload(multipartFile).getData();
        logger.debug("返回的url：{}", url);
        return url;
    }

    private MultipartFile getMulFileByPath(String picPath) {
        FileItem fileItem = createFileItem(picPath);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }

    private FileItem createFileItem(String filePath) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "file";
        int num = filePath.lastIndexOf(".");
        String extFile = filePath.substring(num);
        FileItem item = factory.createItem(textFieldName, "application/x-www-form-urlencoded", true,
                "MyFileName" + extFile);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try( FileInputStream fis = new FileInputStream(newfile);OutputStream os = item.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, 8192))
                    != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            logger.error("创建失败",e);
        }
        return item;
    }
}
